<template>
  <div class="assign-issue">
    <div class="page-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/issues' }">问题管理</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: `/issues/${$route.params.id}` }">问题详情</el-breadcrumb-item>
        <el-breadcrumb-item>分配问题</el-breadcrumb-item>
      </el-breadcrumb>
      <h1>分配问题</h1>
    </div>

    <div class="content-container">
      <!-- 问题信息 -->
      <div class="issue-info">
        <h3>问题信息</h3>
        <div class="info-grid">
          <div class="info-item">
            <label>问题标题：</label>
            <span>{{ issue.title }}</span>
          </div>
          <div class="info-item">
            <label>问题类型：</label>
            <el-tag :type="getTypeTagType(issue.type) as any">{{ getTypeText(issue.type) }}</el-tag>
          </div>
          <div class="info-item">
            <label>优先级：</label>
            <el-tag :type="getPriorityTagType(issue.priority) as any">{{ getPriorityText(issue.priority) }}</el-tag>
          </div>
          <div class="info-item">
            <label>当前状态：</label>
            <el-tag :type="getStatusTagType(issue.status) as any">{{ getStatusText(issue.status) }}</el-tag>
          </div>
          <div class="info-item">
            <label>当前指派人：</label>
            <span>{{ issue.assignee?.username || '未分配' }}</span>
          </div>
          <div class="info-item">
            <label>创建时间：</label>
            <span>{{ formatDate(issue.createdAt) }}</span>
          </div>
        </div>
      </div>

      <!-- 分配表单 -->
      <div class="assign-form">
        <h3>分配设置</h3>
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
        >
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="指派给" prop="assigneeId">
                <el-select
                  v-model="form.assigneeId"
                  placeholder="请选择指派人"
                  style="width: 100%"
                  filterable
                >
                  <el-option
                    v-for="user in users"
                    :key="user.id"
                    :label="user.username"
                    :value="user.id"
                  >
                    <div class="user-option">
                      <el-avatar :size="24" :src="user.avatar">
                        {{ user.username.charAt(0).toUpperCase() }}
                      </el-avatar>
                      <span class="user-name">{{ user.username }}</span>
                      <span class="user-role">{{ user.role }}</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="优先级" prop="priority">
                <el-select v-model="form.priority" placeholder="请选择优先级" style="width: 100%">
                  <el-option label="紧急" value="urgent" />
                  <el-option label="高" value="high" />
                  <el-option label="中" value="medium" />
                  <el-option label="低" value="low" />
                </el-select>
              </el-form-item>

              <el-form-item label="截止日期" prop="dueDate">
                <el-date-picker
                  v-model="form.dueDate"
                  type="datetime"
                  placeholder="请选择截止日期"
                  style="width: 100%"
                  :disabled-date="(time: Date) => time.getTime() < Date.now() - 8.64e7"
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="分配说明" prop="assignNote">
                <el-input
                  v-model="form.assignNote"
                  type="textarea"
                  :rows="6"
                  placeholder="请输入分配说明或特殊要求..."
                  maxlength="500"
                  show-word-limit
                />
              </el-form-item>

              <el-form-item>
                <el-checkbox v-model="form.notifyAssignee">
                  通知指派人
                </el-checkbox>
              </el-form-item>

              <el-form-item>
                <el-checkbox v-model="form.changeStatus">
                  同时将状态更改为"处理中"
                </el-checkbox>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item>
            <el-button type="primary" @click="handleAssign" :loading="loading">
              确认分配
            </el-button>
            <el-button @click="handleCancel">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import dayjs from 'dayjs'

const router = useRouter()
const route = useRoute()
const formRef = ref<FormInstance>()
const loading = ref(false)

// 问题信息
const issue = ref({
  id: 1,
  title: '用户登录页面样式错乱',
  type: 'bug',
  priority: 'high',
  status: 'open',
  assignee: null as any,
  createdAt: new Date('2024-01-15')
})

// 表单数据
const form = reactive({
  assigneeId: null as number | null,
  priority: '',
  dueDate: null as Date | null,
  assignNote: '',
  notifyAssignee: true,
  changeStatus: true
})

// 表单验证规则
const rules: FormRules = {
  assigneeId: [
    { required: true, message: '请选择指派人', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ]
}

// 用户列表
const users = ref([
  {
    id: 1,
    username: '张三',
    role: '开发工程师',
    avatar: ''
  },
  {
    id: 2,
    username: '李四',
    role: '测试工程师',
    avatar: ''
  },
  {
    id: 3,
    username: '王五',
    role: '产品经理',
    avatar: ''
  },
  {
    id: 4,
    username: '赵六',
    role: '项目经理',
    avatar: ''
  }
])

// 加载问题数据
const loadIssue = async () => {
  const issueId = route.params.id
  // 模拟加载问题数据
  const mockIssue = {
    id: Number(issueId),
    title: '用户登录页面样式错乱',
    type: 'bug',
    priority: 'high',
    status: 'open',
    assignee: null,
    createdAt: new Date('2024-01-15')
  }
  
  issue.value = mockIssue
  form.priority = mockIssue.priority
}

// 获取类型标签类型
const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    bug: 'danger',
    feature: 'success',
    improvement: 'warning',
    task: 'info'
  }
  return typeMap[type] || 'info'
}

// 获取类型文本
const getTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    bug: '缺陷',
    feature: '功能请求',
    improvement: '改进',
    task: '任务'
  }
  return typeMap[type] || type
}

// 获取优先级标签类型
const getPriorityTagType = (priority: string) => {
  const priorityMap: Record<string, string> = {
    urgent: 'danger',
    high: 'warning',
    medium: 'info',
    low: 'success'
  }
  return priorityMap[priority] || 'info'
}

// 获取优先级文本
const getPriorityText = (priority: string) => {
  const priorityMap: Record<string, string> = {
    urgent: '紧急',
    high: '高',
    medium: '中',
    low: '低'
  }
  return priorityMap[priority] || priority
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    open: 'info',
    in_progress: 'warning',
    resolved: 'success',
    closed: 'info'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    open: '待处理',
    in_progress: '处理中',
    resolved: '已解决',
    closed: '已关闭'
  }
  return statusMap[status] || status
}

// 格式化日期
const formatDate = (date: Date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}

// 确认分配
const handleAssign = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const assigneeName = users.value.find(u => u.id === form.assigneeId)?.username
    ElMessage.success(`问题已成功分配给 ${assigneeName}`)
    router.push(`/issues/${route.params.id}`)
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

// 取消分配
const handleCancel = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要取消分配吗？',
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '继续分配',
        type: 'warning'
      }
    )
    router.push(`/issues/${route.params.id}`)
  } catch {
    // 用户取消操作
  }
}

onMounted(() => {
  loadIssue()
})
</script>

<style scoped>
.assign-issue {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 16px 0 0 0;
  font-size: 24px;
  color: #333;
}

.content-container {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.issue-info {
  margin-bottom: 32px;
  padding-bottom: 24px;
  border-bottom: 1px solid #e6e6e6;
}

.issue-info h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  color: #333;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-item label {
  font-weight: 500;
  color: #666;
  margin-right: 8px;
  min-width: 80px;
}

.assign-form h3 {
  margin: 0 0 24px 0;
  font-size: 18px;
  color: #333;
}

.user-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-name {
  font-weight: 500;
}

.user-role {
  color: #999;
  font-size: 12px;
  margin-left: auto;
}

.el-form-item {
  margin-bottom: 24px;
}
</style>